import 'package:flutter/material.dart';
import 'package:ichinesereader/models/book/MaxScore.dart';
import 'package:ichinesereader/models/report/studentActivityResult.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/dialogs/maxQuizDialog.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';

// ignore: must_be_immutable
class StudentActivityDataGrid extends StatelessWidget {
  StudentActivityDataGrid(this.dataGrid);

  List<StudentActivityReport> dataGrid;
  bool isWebOrDesktop = GetPlatform.isMacOS || GetPlatform.isWeb;
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  DataGridController _dataGridController = DataGridController();

  @override
  Widget build(BuildContext context) {
    Log.debug('build StudentActivityDataGrid');

    return this.dataGrid.isNotEmpty
        ? Column(children: [Expanded(child: _buildDataGrid())])
        : Center(child: Text('Data not available ...'));
  }

  SfDataGrid _buildDataGrid() {
    return SfDataGrid(
      source: AssignmentDataGridSource(items: dataGrid),
      onQueryRowHeight: (row) {
        return row.rowIndex == 0 ? 50.0 : 49.0;
      },
      //设置表头高度
      allowSorting: true,
      allowTriStateSorting: true,
      allowSwiping: false,
      controller: _dataGridController,
      navigationMode: GridNavigationMode.row,
      endSwipeActionsBuilder:
          (BuildContext context, DataGridRow row, int rowIndex) {
        return GestureDetector(
            onTap: () {},
            child: Container(
                color: Colors.redAccent,
                child: Center(
                  child: Icon(Icons.delete),
                )));
      },
      columns: <GridColumn>[
        GridColumn(
          columnName: 'Date',
          width: 180,
          label: buildDataGridColumnLabel('Date'),
        ),
        GridColumn(
          columnName: 'Type',
          width: 180,
          label: buildDataGridColumnLabel('Activity Type'),
        ),
        GridColumn(
          width: 180,
          columnName: 'Score',
          label: buildDataGridColumnLabel('Score'),
        ),
        GridColumn(
          width: 180,
          columnName: 'Content',
          label: buildDataGridColumnLabel('Content'),
        ),
        GridColumn(
          columnName: 'Assignment',
          width: 180,
          label: buildDataGridColumnLabel('Homework'),
        ),
        GridColumn(
          columnName: 'Data',
          width: 180,
          visible: false,
          label: Container(
            child: Text('Data'.tr),
          ),
        ),
      ],
    );
  }
}

class AssignmentDataGridSource extends DataGridSource {
  AssignmentDataGridSource({required List<StudentActivityReport> items}) {
    dataGridRows = items
        .map<DataGridRow>((dataGridRow) => DataGridRow(cells: [
              DataGridCell<int>(columnName: 'Date', value: dataGridRow.when),
              DataGridCell<String>(columnName: 'Type', value: dataGridRow.type),
              DataGridCell<int>(
                  columnName: 'Score', value: dataGridRow.percentage),
              DataGridCell<String>(
                  columnName: 'Content', value: dataGridRow.bookTitle),
              DataGridCell<String>(
                  columnName: 'Assignment', value: dataGridRow.assignmentName),
              DataGridCell<StudentActivityReport>(
                  columnName: 'Data', value: dataGridRow)
            ]))
        .toList();
  }

  List<DataGridRow> dataGridRows = [];

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter? buildRow(DataGridRow row) {
    //列表隔行Row的颜色 // https://help.syncfusion.com/flutter/datagrid/conditional-styling
    Color setRowBackgroundColor() {
      final int index = effectiveRows.indexOf(row);
      if (index % 2 != 0) {
        return Get.isDarkMode ? Colors.black : Colors.grey[200]!;
      }
      return Colors.transparent;
    }

    return DataGridRowAdapter(
        color: setRowBackgroundColor(),
        cells: row.getCells().map<Widget>((dataGridCell) {
          if (dataGridCell.columnName == 'Date') {
            if (dataGridCell.value > 0) {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    DateFormat('yyyy-MM-dd kk:mm').format(
                        DateTime.fromMillisecondsSinceEpoch(
                            dataGridCell.value)),
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            } else {
              return Container(
                  alignment: Alignment.center,
                  padding: EdgeInsets.symmetric(horizontal: 16.0),
                  child: Text(
                    '--',
                    overflow: TextOverflow.ellipsis,
                    style: Get.textTheme.bodySmall,
                  ));
            }
          } else if (dataGridCell.columnName == "Score") {
            var data = row
                .getCells()
                .where((element) => element.columnName == 'Data')
                .first
                .value;
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: GestureDetector(
                onTap: () {
                  if (dataGridCell.value != null) {
                    showGeneralDialog(
                        context: Get.context!,
                        transitionDuration: Duration(milliseconds: 400),
                        pageBuilder: (bc, ania, anis) {
                          return MaxQuizDialog(
                            bookId: data.bookId,
                            maxScore: new MaxScore(
                                when: data.when,
                                submittedAnswers: data.submittedAnswers,
                                score: data.score,
                                simple: data.simple),
                          );
                        });
                  }
                },
                child: Text(
                  dataGridCell.value != null
                      ? '${dataGridCell.value.toString()}%'
                      : '--',
                  softWrap: true,
                  style: dataGridCell.value != null
                      ? Get.textTheme.titleLarge
                      : Get.textTheme.bodySmall,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            );
          } else if (dataGridCell.columnName == "Assignment" ||
              dataGridCell.columnName == "Content") {
            return Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16.0),
              child: Text(
                dataGridCell.value != null ? dataGridCell.value : "--",
                softWrap: true,
                style: Get.textTheme.bodySmall,
                overflow: TextOverflow.ellipsis,
              ),
            );
          } else {
            return Container(
                alignment: Alignment.center,
                padding: EdgeInsets.symmetric(horizontal: 16.0),
                child: Text(
                  dataGridCell.value.toString(),
                  softWrap: true,
                  overflow: TextOverflow.ellipsis,
                  style: Get.textTheme.bodySmall,
                ));
          }
        }).toList());
  }
}
